﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "SmartAnimSequenceExtensions.h"

#include "UnrealEd/Private/FbxExporter.h"

bool USmartAnimSequenceExtensions::SmClipByFrame(UAnimSequence* AnimSequence, int StartFrame, int EndFrame)
{

	if (StartFrame < 0 || StartFrame > EndFrame)
		return false;

	if (EndFrame > AnimSequence->GetNumberOfFrames())
		EndFrame = AnimSequence->GetNumberOfFrames();

	float NewStartTime = (float)StartFrame / AnimSequence->GetFrameRate();
	
	float NewEndTime = (float)EndFrame / AnimSequence->GetFrameRate();
	
	if (EndFrame < AnimSequence->GetNumberOfFrames())
	{
		if (!AnimSequence->CropRawAnimData(NewEndTime, false))
			return false;
	}
	if (StartFrame > 0)
	{
		if (!AnimSequence->CropRawAnimData(NewStartTime, true))
			return false;
	}
	AnimSequence->SequenceLength = NewEndTime- NewStartTime;
	AnimSequence->PostProcessSequence();
	return true;

}

bool USmartAnimSequenceExtensions::SmClipByTime(UAnimSequence* AnimSequence, float StartTime, float EndTime)
{
	
	if (!AnimSequence) return false;
	if (StartTime < 0 || StartTime > EndTime)
		return false;
	if (EndTime > AnimSequence->SequenceLength)
		EndTime =  AnimSequence->SequenceLength;
	
	if (!AnimSequence->CropRawAnimData(EndTime, false))
		return false;
	if (!AnimSequence->CropRawAnimData(EndTime, true))
		return false;
	AnimSequence->PostProcessSequence();
	return true;
}

float USmartAnimSequenceExtensions::SmGetRate(UAnimSequence* AnimSequence)
{
	return AnimSequence->GetFrameRate();
}

void USmartAnimSequenceExtensions::SmExportFbx(UAnimSequence* AnimSequence, FString OutPath,
	UFbxExportOption* Options=nullptr)
{
	bool bCanceled;
	bool Auto=true;
	if(!OutPath.IsEmpty())
	{
		USkeletalMesh* Mesh = AnimSequence->GetSkeleton()->FindCompatibleMesh();
		UnFbx::FFbxExporter* Exporter = UnFbx::FFbxExporter::GetInstance();
		if(IsValid(Options))
		{
			Exporter->SetExportOptionsOverride(Options);
		}
		Exporter->FillExportOptions(true, false, OutPath, bCanceled, Auto);
		Exporter->CreateDocument();
		Exporter->ExportAnimSequence(AnimSequence, Mesh, Exporter->GetExportOptions()->bExportPreviewMesh);
		Exporter->WriteToFile(*OutPath);
	}
}
